<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="题干" prop="content">
        <el-input
          v-model="queryParams.content"
          placeholder="请输入题干部分"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="题目类型" prop="type">
        <el-select
          v-model="queryParams.type"
          placeholder="题目类型"
          clearable
        >
          <el-option
            v-for="item in typeList"
            :key="item.type"
            :label="item.label"
            :value="item.type"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="题库类型" prop="bankType">
        <el-select
          v-model="queryParams.bankType"
          placeholder="题库类型"
          clearable
        >
          <el-option
            v-for="item in bankTypeList"
            :key="item.type"
            :label="item.label"
            :value="item.type"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="所属科目" prop="courseNo">
        <el-select
          v-model="queryParams.courseNo"
          placeholder="所属科目"
          clearable
        >
          <el-option
            v-for="item in courseList"
            :key="item.courseNo"
            :label="item.courseTypeName + ' - ' + item.courseName"
            :value="item.courseNo"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>


    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['exam:add']"
        >新增</el-button>
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['exam:import']"
        >导入</el-button>
          <el-button
            type="success"
            plain
            icon="el-icon-circle-plus-outline"
            size="mini"
            :disabled="multiple"
            @click="handleInsertPaper"
            v-hasPermi="['system:user:remove']"
          >添加到试卷</el-button>
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>


    <el-table
      ref="tables"
      v-loading="loading"
      :data="questionList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column label="题干" align="center" prop="content" />
      <el-table-column label="选项" align="center" prop="optionStr" />
      <el-table-column label="答案" align="center" prop="answer" />
      <el-table-column label="题型" align="center" prop="type" >
        <template slot-scope="scope">
              <span>{{
                  matchType(scope.row.type)
                }}</span>
        </template>
      </el-table-column>
      <el-table-column label="解析" align="center" prop="analysis" />
      <el-table-column label="题库类型" align="center" prop="bankType" >
        <template slot-scope="scope">
              <span>{{
                  matchBankType(scope.row.bankType)
                }}</span>
        </template>
      </el-table-column>
      <el-table-column label="所属科目" align="center" prop="courseNo" >
        <template slot-scope="scope">
              <span>{{
                  matchCourseNo(scope.row.courseNo)
                }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="160"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-row>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['questionBank:update']"
              >修改</el-button
            >
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDel(scope.row)"
              v-hasPermi="['questionBank:del']"
              >删除</el-button
            >
            <el-button
              size="mini"
              type="text"
              icon="el-icon-plus"
              @click="handleInsetPaper(scope.row)"
              v-hasPermi="['exam:update']"
              >添加到试卷</el-button
            >
          </el-row>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNo"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />


    <!-- 新增 -->
    <el-dialog
      :title="addTitle"
      :visible.sync="addQuestionView"
      width="1400px"
      append-to-body
    >
      <el-form ref="form" :model="addQuestionForm" label-width="80px">
        <el-form-item label="题干" prop="content">
          <el-input type="textarea" v-model="addQuestionForm.content" placeholder="请输入题干" />
        </el-form-item>
        <el-form-item label="选项" prop="optionStr">
          <el-input type="textarea" v-model="addQuestionForm.optionStr" placeholder="请输入选项（选项间用 | 分隔）" />
        </el-form-item>
        <el-form-item label="答案" prop="answer">
          <el-input type="textarea" v-model="addQuestionForm.answer" placeholder="请输入答案（多选题用 & 分隔）" />
        </el-form-item>
        <el-form-item label="解析" prop="analysis">
          <el-input type="textarea" v-model="addQuestionForm.analysis" placeholder="请输入解析" />
        </el-form-item>
        <el-form-item label="题型" prop="type">
          <el-select
            v-model="addQuestionForm.type"
            placeholder="题型"
            clearable
          >
            <el-option
              v-for="item in typeList"
              :key="item.type"
              :label="item.label"
              :value="item.type"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="题库类型" prop="bankType">
          <el-select
            v-model="addQuestionForm.bankType"
            placeholder="题库类型"
            clearable
          >
            <el-option
              v-for="item in bankTypeList"
              :key="item.type"
              :label="item.label"
              :value="item.type"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所属科目" prop="courseNo">
          <el-select
            v-model="addQuestionForm.courseNo"
            placeholder="题库类型"
            clearable
          >
            <el-option
              v-for="item in courseList"
              :key="item.courseNo"
              :label="item.courseTypeName + ' - ' + item.courseName"
              :value="item.courseNo"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="addQuestionForm.sort" placeholder="排序" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAddQuestionForm">确 定</el-button>
        <el-button @click="addQuestionView = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 修改 -->
    <el-dialog
      :title="addTitle"
      :visible.sync="updateQuestionView"
      width="1400px"
      append-to-body
    >
      <el-form ref="form" :model="updateQuestionView" label-width="80px">
        <el-form-item label="题干" prop="content">
          <el-input type="textarea" v-model="updateQuestionForm.content" placeholder="请输入题干" />
        </el-form-item>
        <el-form-item label="选项" prop="optionStr">
          <el-input type="textarea" v-model="updateQuestionForm.optionStr" placeholder="请输入选项（选项间用 | 分隔）" />
        </el-form-item>
        <el-form-item label="答案" prop="answer">
          <el-input type="textarea" v-model="updateQuestionForm.answer" placeholder="请输入答案（多选题用 & 分隔）" />
        </el-form-item>
        <el-form-item label="解析" prop="analysis">
          <el-input type="textarea" v-model="updateQuestionForm.analysis" placeholder="请输入解析" />
        </el-form-item>
        <el-form-item label="题型" prop="type">
          <el-select
            v-model="updateQuestionForm.type"
            placeholder="题型"
            clearable
          >
            <el-option
              v-for="item in typeList"
              :key="item.type"
              :label="item.label"
              :value="item.type"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="题库类型" prop="bankType">
          <el-select
            v-model="updateQuestionForm.bankType"
            placeholder="题库类型"
            clearable
          >
            <el-option
              v-for="item in bankTypeList"
              :key="item.type"
              :label="item.label"
              :value="item.type"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所属科目" prop="courseNo">
          <el-select
            v-model="updateQuestionForm.courseNo"
            placeholder="题库类型"
            clearable
          >
            <el-option
              v-for="item in courseList"
              :key="item.courseNo"
              :label="item.courseTypeName + ' - ' + item.courseName"
              :value="item.courseNo"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="updateQuestionForm.sort" placeholder="排序" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitUpdateQuestionForm">确 定</el-button>
        <el-button @click="updateQuestionView = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + true"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <p>仅允许导入xls、xlsx格式文件。</p>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="添加到试卷" :visible.sync="paper.open" width="400px" append-to-body>
    <!--  selected    -->
      <el-form ref="form" :model="paper.data" label-width="80px">
        <el-form-item label="试卷" prop="id">
          <el-select
            v-model="paper.data.id"
            placeholder="试卷"
            clearable
          >
            <el-option
              v-for="item in paper.list"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="sort" v-if="paper.data.qid">
          <el-input type="text" v-model="paper.data.sort" placeholder="请输入排序" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAddToPaper">确 定</el-button>
        <el-button @click="paper.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listQuestion, addQuestion, updateQuestion, delQuestion } from '@/api/questionBank/question'
import { isArray } from 'util'
import { getToken } from '@/utils/auth'
import { wholeList } from "@/api/course/course";
import { all, insertQuestion } from '@/api/exam/paper'
import { delUser } from '@/api/system/user'

export default {
  name: "Exam",
  data() {
    return {
      queryParams: {
        content: null,
        type: null,
        createPerson: null,
        bankType: null,
        courseNo: null,

        pageNo: 0,
        pageSize: 10,
      },
      startDateRange: [],
      endDateRange: [],

      showSearch: true,

      ids: [],
      // 非多个禁用
      multiple: true,

      typeList: [
        {type: 1 , label: '单选题'},
        {type: 2 , label: '多选题'},
        {type: 3 , label: '判断题'},
        {type: 4 , label: '填空题'}
      ],
      bankTypeList: [
        {type: 0 , label: '考核题库'},
        {type: 1 , label: '训练题库'},
      ],
      courseList:[],

      loading: true,
      questionList: null,
      total: 0,

      title: '题目详情',
      subjectView: false, //科目详情页是否弹出
      subjectInfo: null,

      addQuestionView: false,
      addTitle: '新增题目',
      addQuestionForm: {
        content: null,
        optionStr: null,
        answer: null,
        type: null,
        analysis: null,
        bankType: null,
        courseNo: null,
        sort: null,
      },

      updateQuestionView: false,
      updateTitle: '新增题目',
      updateQuestionForm: {
        id: null,
        content: null,
        optionStr: null,
        answer: null,
        type: null,
        bankType: null,
        courseNo: null,
        analysis: null,
        sort: null,
      },

      upload: {
        // 是否显示弹出层（导入）
        open: false,
        // 弹出层标题（导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/questionBank/question/import"
      },

      paper: {
        open: false,
        list: [],
        data: {
        },
      }
    };
  },
  created() {
    if(this.$route.params.courseNo !=null){
      this.queryParams.courseNo = this.$route.params.courseNo;
      this.queryParams.bankType = 1;
      this.$route.params.courseNo = null;
    }
    this.getCourseList();
    this.getPaperList();
    this.getList();
  },
  methods: {
    /** 查询任务列表 */
    getList() {
      this.loading = true;
      // this.addDateRange(this.queryParams, this.startDateRange ,'StartTime');
      // this.addDateRange(this.queryParams, this.endDateRange ,'EndTime');
      let param = {...this.queryParams};
      param.pageNo --;
      listQuestion(param).then(
        (response) => {
          this.questionList = response.rows;
          this.total = parseInt(response.total);
          this.loading = false;
        }
      );
    },
    async getCourseList(){
       await wholeList().then(resp => {
        this.courseList = resp.data;
      });
    },
    async getPaperList(){
      await all().then(resp => {
        this.paper.list = resp.data;
      });
    },
    matchType(type){
      for (let t of this.typeList){
        if(t.type == type){
          return t.label;
        }
      }
    },
    matchBankType(type){
      for (let t of this.bankTypeList){
        if(t.type == type){
          return t.label;
        }
      }
    },
    matchCourseNo(courseNo){
      if(courseNo == 0){
        return '-';
      }
      for (let t of this.courseList){
        if(t.courseNo == courseNo){
          return t.courseTypeName + ' - ' + t.courseName;
        }
      }
    },

    categoryVal(categoryId){
      for (let c of this.categoryList){
        if(c.category == categoryId){
          return c.name;
        }
      }
    },
    subjectVal(categoryId ,subjectId){
      for (let c of this.categoryList){
        if(c.category == categoryId){
          for(let s of c.subjects){
            if(s.id == subjectId){
              return s.name;
            }
          }
        }
      }
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.startDateRange = [];
      this.endDateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },


    /** 详细按钮操作 */
    handleView(row) {
      this.taskNo = row.taskNo;
      this.taskView = true;
      const taskId = row.taskId;
      getTask(taskId).then((response) => {
        this.evaluate = response.data;
        this.title = "考核详情";
      });

      //人员信息
      this.getPersonlTaskList();
    },

    handleAdd(){
      this.addQuestionView = true;
    },
    handleImport() {
      this.upload.title = "题目导入";
      this.upload.open = true;
    },
    handleInsertPaper(){
      this.handleInsetPaper({'qidList': this.ids});
    },

    /** 下载模板操作 */
    importTemplate() {
      this.download('questionBank/question/importTemplate', {
      }, `题目导入模板.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.updateQuestionForm = {
        id : row.id,
        content: row.content,
        optionStr: row.optionStr,
        answer: row.answer,
        type: row.type,
        analysis: row.analysis,
        sort: row.sort
      };
      this.updateQuestionView = true;
    },
    handleDel(row){
      this.$confirm('是否确认删除此题?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delQuestion(row.id).then(resp => {
          this.getList();
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        })
      });
    },
    handleInsetPaper(row){
      this.paper.open = true;
      this.paper.data.qid = row.id;
      this.paper.data.qidList = row.qidList;
    },
    submitAddToPaper(){
      insertQuestion(this.paper.data).then(rsp => {
        this.paper.open = false;
        this.$message({
          type: 'success',
          message: '添加成功'
        });
      });
    },

    submitAddQuestionForm(){
        console.log(this.addQuestionForm);
        addQuestion(this.addQuestionForm).then(resp => {
          this.getList();
          this.$modal.msgSuccess("新增成功");
          this.addQuestionView = false;
        });
    },

    submitUpdateQuestionForm(){
      console.log(this.updateQuestionForm);
      updateQuestion(this.updateQuestionForm).then(resp => {
        this.getList();
        this.$modal.msgSuccess("修改成功");
        this.updateQuestionView = false;
      });
    },
  },
};
</script>
